package com.jiangkang.example.util;

import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.BasicHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HttpClientUtil {
	private static Logger logger = LoggerFactory.getLogger(HttpClientUtil.class);
	
	public static String post(String url,String data,String type) throws Exception {

		HttpClient httpClient = buildHttpClient();
		HttpPost httpPost = new HttpPost(url);
		RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(Constants.READ_TIMEOUT_MS)
				.setConnectTimeout(Constants.CONNECT_TIMEOUT_MS).build();
		httpPost.setConfig(requestConfig);
		httpPost.addHeader("Content-Type", type);//"application/json"
		StringEntity postEntity = new StringEntity(data, Constants.CHARSET_UTF8);
		httpPost.setEntity(postEntity);

		HttpResponse httpResponse = httpClient.execute(httpPost);
		HttpEntity httpEntity = httpResponse.getEntity();
		String result = EntityUtils.toString(httpEntity, Constants.CHARSET_UTF8);
		return result;
	}
	
	public static String postWithParams(String url, List<NameValuePair> params,String type) throws Exception {
		HttpClient httpClient = buildHttpClient();
		HttpPost httpPost = new HttpPost(url);
		RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(Constants.READ_TIMEOUT_MS)
				.setConnectTimeout(Constants.CONNECT_TIMEOUT_MS).build();
		httpPost.setConfig(requestConfig);
		httpPost.addHeader("Content-Type", type);//"application/x-www-form-urlencoded"
		if(params!=null) {
			httpPost.setEntity(new UrlEncodedFormEntity(params, Constants.CHARSET_UTF8));
		}
		HttpResponse httpResponse = httpClient.execute(httpPost);
		HttpEntity httpEntity = httpResponse.getEntity();
		String result = EntityUtils.toString(httpEntity, Constants.CHARSET_UTF8);
		return result;
	}
	
	public static InputStream get(String url) throws Exception {
		HttpClient httpClient = buildHttpClient();
		HttpGet httpGet = new HttpGet(url);
		RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(Constants.READ_TIMEOUT_MS)
				.setConnectTimeout(Constants.CONNECT_TIMEOUT_MS).build();
		httpGet.setConfig(requestConfig);
		HttpResponse httpResponse = httpClient.execute(httpGet);
		return httpResponse.getEntity().getContent();
	}
	
	private static HttpClient buildHttpClient() {
		BasicHttpClientConnectionManager connManager ;
		connManager = new BasicHttpClientConnectionManager(
				RegistryBuilder.<ConnectionSocketFactory>create()
						.register(Constants.PROTOCOL_HTTP, PlainConnectionSocketFactory.getSocketFactory())
						.register(Constants.PROTOCOL_HTTPS, SSLConnectionSocketFactory.getSocketFactory()).build(),
				null, null, null);

		HttpClient httpClient = HttpClientBuilder.create().setConnectionManager(connManager).build();
		return httpClient;
	}
	public static String urlEncode(String source, String encode) {  
        String result = source;  
        try {  
            result = URLEncoder.encode(source,  Constants.CHARSET_UTF8);  
        } catch (UnsupportedEncodingException e) {  
        	logger.warn(e.getMessage());
        }  
        return result;  
    }  
}
